<template>
  <div class="health-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>服务健康检查</span>
          <el-button type="primary" @click="handleRefresh" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新检查
          </el-button>
        </div>
      </template>

      <!-- 整体状态 -->
      <div class="status-section">
        <el-alert
          :title="healthData?.status === 'healthy' ? '服务运行正常' : '服务异常'"
          :type="healthData?.status === 'healthy' ? 'success' : 'error'"
          :closable="false"
          show-icon
        >
          <template #default>
            <div class="status-content">
              <div class="status-text">
                <strong>状态：</strong>
                <el-tag :type="healthData?.status === 'healthy' ? 'success' : 'danger'" size="large">
                  {{ healthData?.status === 'healthy' ? '健康' : '异常' }}
                </el-tag>
              </div>
              <div class="timestamp" v-if="healthData?.timestamp">
                <strong>检查时间：</strong>
                {{ formatDate(healthData.timestamp) }}
              </div>
            </div>
          </template>
        </el-alert>
      </div>

      <!-- 服务检查详情 -->
      <div class="checks-section">
        <h3>服务检查详情</h3>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" v-for="(status, service) in healthData?.checks" :key="String(service)">
            <el-card class="service-card" :class="{ 'service-error': !status }">
              <div class="service-content">
                <div class="service-icon">
                  <el-icon :size="40" :color="status ? '#67c23a' : '#f56c6c'">
                    <component :is="status ? 'CircleCheck' : 'CircleClose'" />
                  </el-icon>
                </div>
                <div class="service-info">
                  <div class="service-name">{{ getServiceName(service) }}</div>
                  <div class="service-status">
                    <el-tag :type="status ? 'success' : 'danger'">
                      {{ status ? '正常' : '异常' }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 检查历史（可选，如果需要的话） -->
      <div class="info-section" v-if="healthData">
        <el-descriptions title="详细信息" :column="2" border>
          <el-descriptions-item label="整体状态">
            <el-tag :type="healthData.status === 'healthy' ? 'success' : 'danger'">
              {{ healthData.status === 'healthy' ? '健康' : '异常' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="检查时间">
            {{ formatDate(healthData.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="Koa 服务" :span="2">
            <el-tag :type="healthData.checks.koa ? 'success' : 'danger'">
              {{ healthData.checks.koa ? '正常' : '异常' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="MySQL 数据库" :span="2">
            <el-tag :type="healthData.checks.mysql ? 'success' : 'danger'">
              {{ healthData.checks.mysql ? '正常' : '异常' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Redis 缓存" :span="2">
            <el-tag :type="healthData.checks.redis ? 'success' : 'danger'">
              {{ healthData.checks.redis ? '正常' : '异常' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { checkHealth, type HealthCheckData } from '@/api/health'
import { formatDate } from '@/utils'

const loading = ref(false)
const healthData = ref<HealthCheckData | null>(null)
let refreshInterval: ReturnType<typeof setInterval> | null = null

// 获取服务名称
const getServiceName = (service: string | number) => {
  const serviceStr = String(service)
  const nameMap: Record<string, string> = {
    koa: 'Koa 服务',
    mysql: 'MySQL 数据库',
    redis: 'Redis 缓存'
  }
  return nameMap[serviceStr] || serviceStr.toUpperCase()
}

// 加载健康检查数据
const loadHealthCheck = async () => {
  loading.value = true
  try {
    const res = await checkHealth()
    healthData.value = res.data
  } catch (error: any) {
    ElMessage.error(error.message || '健康检查失败')
    // 如果检查失败，设置异常状态
    healthData.value = {
      status: 'unhealthy',
      checks: {},
      timestamp: new Date().toISOString()
    }
  } finally {
    loading.value = false
  }
}

// 刷新检查
const handleRefresh = () => {
  loadHealthCheck()
}

onMounted(() => {
  loadHealthCheck()
  // 每30秒自动刷新一次
  refreshInterval = setInterval(() => {
    loadHealthCheck()
  }, 30000)
})

onUnmounted(() => {
  // 组件卸载时清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
})
</script>

<style scoped lang="scss">
.health-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .status-section {
    margin-bottom: 30px;

    .status-content {
      display: flex;
      flex-direction: column;
      gap: 10px;

      .status-text {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .timestamp {
        color: #909399;
        font-size: 14px;
      }
    }
  }

  .checks-section {
    margin-bottom: 30px;

    h3 {
      margin-bottom: 20px;
      color: #303133;
    }

    .service-card {
      margin-bottom: 20px;
      transition: all 0.3s;

      &.service-error {
        border-color: #f56c6c;
      }

      .service-content {
        display: flex;
        align-items: center;
        gap: 15px;

        .service-icon {
          flex-shrink: 0;
        }

        .service-info {
          flex: 1;

          .service-name {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            color: #303133;
          }

          .service-status {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }

  .info-section {
    margin-top: 30px;
  }
}
</style>

